package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * kafka消费者
 *
 * 只有在同一组里面的消息  才能消费一次
 */
public class ConsumerQuickStart {
    public static void main(String[] args) {
        Properties properties = new Properties();
        //获取kafka的连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "8.142.73.187:9092");
        //设置key反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //设置value反序列化
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //设置消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");


        //获取消费者对象
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer(properties);

        //订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("itheima-topic"));

        while (true) {
            //获取消息
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));

            for (ConsumerRecord<String, String> record : records) {
                String key = record.key();
                String value = record.value();
                System.out.println(key);
                System.out.println(value);
            }
        }


    }
}

class ConsumerQuickStart1 {
    public static void main(String[] args) {
        Properties properties = new Properties();
        //获取kafka的连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "8.142.73.187:9092");
        //设置key反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //设置value反序列化
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //设置消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");


        //获取消费者对象
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer(properties);

        //订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("itheima-topic"));

        while (true) {
            //获取消息
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));

            for (ConsumerRecord<String, String> record : records) {
                String key = record.key();
                String value = record.value();
                System.out.println(key);
                System.out.println(value);
            }
        }


    }
}
